package com.jx.service.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jx.pojo.entity.content.Article;
import com.jx.pojo.entity.content.Category;
import com.jx.pojo.po.content.SidebarMenuPO;
import com.jx.service.content.ArticleService;
import com.jx.service.content.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CategoryApiService {

    @Resource
    private ArticleService articleService;

    @Resource
    private CategoryService categoryService;


    public List<SidebarMenuPO> listAllMenus() {

        // 全部菜单
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1);
        wrapper.orderByAsc("sort");
        List<Category> list = categoryService.list(wrapper);

        // 二级菜单
        Map<Integer, List<Category>> secondCategoryMap = list.stream().filter(s -> s.getType() == 2)
                .collect(Collectors.groupingBy(Category::getParentId));

        // 文章列表
        List<Article> articles = articleService.listAll();
        Map<Integer, List<Article>> articleMap = articles.stream().filter(s -> s.getCategoryId() != null).collect(Collectors.groupingBy(Article::getCategoryId));

        // 一级菜单
        List<Category> firstCategoryList = list.stream().filter(s -> s.getParentId() == 0).collect(Collectors.toList());

        List<SidebarMenuPO> result = new ArrayList<>();
        for (Category category : firstCategoryList) {
            List<Category> categories = secondCategoryMap.get(category.getId());
            List<SidebarMenuPO> children = new ArrayList<>();
            for (Category c : categories) {
                List<Article> articleList = articleMap.get(c.getId());
                List<SidebarMenuPO> articlePOList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(articleList)) {
                    articlePOList = articleList.stream()
                            .map(s -> new SidebarMenuPO(s.getId(), s.getTitle(), "/doc/" + s.getId(), null)).collect(Collectors.toList());
                }
                SidebarMenuPO po = new SidebarMenuPO(c.getId(), c.getCategoryName(), c.getId() + "", articlePOList);
                children.add(po);
            }
            SidebarMenuPO po = new SidebarMenuPO(category.getId(), category.getCategoryName(), category.getId() + "", children);
            result.add(po);
        }
        return result;
    }

}
